package middleware

import (
	"blog_server/pkg/app"
	"blog_server/pkg/errcode"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		eCode := errcode.Success
		method := c.Request.Method
		token := c.GetHeader("X-Token")
		if token == "" {
			eCode = errcode.InvalidParams
		}
		claims, err := app.ParseToken(token)
		if err != nil {
			switch err.(*jwt.ValidationError).Errors {
			case jwt.ValidationErrorExpired:
				eCode = errcode.UnauthorizedTokenTimeout
			default:
				eCode = errcode.UnauthorizedTokenError
			}
		}
		if claims.Role != "admin" && method != "get" {
			eCode = errcode.Unauthorized
		}
		if eCode != errcode.Success {
			response := app.NewResponse(c)
			response.ToErrorResponse(eCode)
			c.Abort()
			return
		}
		c.Next()
	}
}
